﻿using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using com.nm.library.Helper;
using EntityFramework.Extensions;
using NHibernateVertica;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.library;

namespace BaseAPI
{
    [Description("用户数据组权限管理")]
    public class DataGroupHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        [MustLogin]
        [Description("待选列表")]
        [ReturnType(typeof(IList<ListData>))]
        public ApiResult GetCehckedDataList([ParamDescription("组编号")]string GroupDataID)
        {
            if (string.IsNullOrWhiteSpace(GroupDataID)) return Error("【组编号】不能空！");
            //所有省份
            var sql = $@"SELECT distinct ebap.AreaID as ParentAreaID,ebap.AreaName as ParentAreaName,
                        gv.dictValue as DistrictID,gv.dictName as DistrictName
                        FROM dw.dw_Shop dw
                        left join ods.ods_erp_Bas_Area eba on eba.AreaID = dw.AreaID
                        left join ods.ods_erp_Bas_Area ebap on ebap.AreaID=eba.ParentID
                        left join ods.ods_erp_Bas_OperationArea eboa on eboa.OperationAreaID=dw.OperationAreaID
                        left join dw.dw_AreaProCity apc on dw.AreaID = apc.AreaID
                        left join ods.ods_erp_Bas_Stock ebs on apc.StockID=ebs.StockID
                        left join dw.dw_global_dictionary gv on apc.ParentAreaID = gv.dictValue  
                        where 1=1 and dw.CompanyID='{UserInfo.UserCompanyId}' order by gv.dictValue";
            var cmd = Helper.GetSqlStringCommand(sql);
            var dt = Helper.ExecuteDataTable(cmd);
            var list = ModelConvertHelper<AreaData>.ConvertToModel(dt).GroupBy(t => t.DistrictID).OrderBy(d => d.Key).ToList();
            //被选中省份
            var dc = new SysEntities();
            var qurey = (from a in dc.sys_data_group
                         where a.DataType == 0 && a.GroupDataID == GroupDataID
                         select new
                         {
                             a.DataValue
                         }).ToList().Select(o => new CheckData {
                             Value = o.DataValue
                         }).ToList();
            var result = new ListData
            {
                GroupDataID = GroupDataID,
                AllDataList = list,
                CheckDataList = qurey
            };
            return Success(result);
        }

        [MustLogin]
        [Description("数据组对应的用户")]
        [ReturnType(typeof(IList<UserList>))]
        public ApiResult GetGroupUserList([ParamDescription("组编号")]string GroupDataID)
        {
            if (string.IsNullOrWhiteSpace(GroupDataID)) return Error("【组编号】不能空！");
            var dc = new SysEntities();
            var result = (from a in dc.sys_userData_group
                         join b in dc.sys_users on a.UserID equals b.UserID
                         where a.GroupDataID == GroupDataID
                         select b).Select(o => new UserList
                         {
                             UserID = o.UserID,
                             UserName = o.UserName
                         }).ToList();
            return Success(result);
        }

        [MustLogin]
        [Description("所有用户列表")]
        [ReturnType(typeof(IList<UserList>))]
        public ApiResult GetAllUserList([ParamDescription("账号/名称模糊查找")] string Keys)
        {
            var dc = new SysEntities();
            var qurey = (from a in dc.sys_users
                         where a.IsEffective && a.IsRemove == false
                         select a);
            if (!string.IsNullOrWhiteSpace(Keys))
            {
                qurey.Where(t => t.UserName.Contains(Keys) || t.LoginAccount.Contains(Keys));
            }
            var result = qurey.Select(o => new UserList
            {
                UserID = o.UserID,
                UserCode = o.UserNo,
                UserName = o.UserName
            }).ToList();
            return Success(result);
        }
        [JsonType]
        [MustLogin]
        [Description("修改数据组权限")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult ModifyGroup(ModifyData param)
        {
            if (param == null) return Error("参数对象不能为空！");
            if (string.IsNullOrWhiteSpace(param.GroupDataID)) return Error("数据组编号不能空！");
            if (param.Arealist == null) return Error("参数不能空！");
            var dc = new SysEntities();
            var tran = dc.Database.BeginTransaction();
            dc.sys_data_group.Where(t => t.GroupDataID == param.GroupDataID).Delete();
            dc.sys_userData_group.Where(t => t.GroupDataID == param.GroupDataID).Delete();
            //添加省份
            if (param.Arealist != null)
            {
                foreach (var item in param.Arealist)
                {
                    var gruop = new sys_data_group
                    {
                        GroupDataID = param.GroupDataID,
                        DistrictID = item.DistrictID,
                        DataType = 0,
                        DataValue = item.AreaID,
                        CreateDate = DateTime.Now,
                        ModifyDate = DateTime.Now,
                        Operator = this.UserId
                    };
                    dc.sys_data_group.Add(gruop);
                }
            }
            //添加用户
            if (param.UserList != null)
            {
                foreach (var item in param.UserList)
                {
                    var user = new sys_userData_group
                    {
                        GroupDataID = param.GroupDataID,
                        UserID = item,
                        CreateDate = DateTime.Now,
                        Operator = this.UserId
                    };
                    dc.sys_userData_group.Add(user);
                }
            }
            try
            {
                dc.SaveChanges();
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                Error(ex.Message);
            }
            return Success(0);
        }

        [Description("列表数据")]
        public class ListData
        {
            [ParamDescription("组编号")]
            public string GroupDataID { get; set; }
            [ParamDescription("所有列表")]
            public IList<IGrouping<string,AreaData>> AllDataList { get; set; }
            [ParamDescription("已选列表")]
            public IList<CheckData> CheckDataList { get; set; }
        }
        [Description("所有区域数据")]
        public class AreaData
        {
            [ParamDescription("省份ID")]
            public string ParentAreaID { get; set; }
            [ParamDescription("省份")]
            public string ParentAreaName { get; set; }
            [ParamDescription("大区ID")]
            public string DistrictID { get; set; }
            [ParamDescription("大区名称")]
            public string DistrictName { get; set; }
        }
        [Description("选中数据")]
        public class CheckData
        {
            [ParamDescription("值")]
            public string Value { get; set; }
        }
        [Description("修改数据对象")]
        public class ModifyData
        {
            [ParamDescription("组编号")]
            public string GroupDataID { get; set; }
            [ParamDescription("省份列表")]
            public IList<BigAreaDAta> Arealist { get; set; }
            [ParamDescription("用户")]
            public IList<int> UserList { get; set; }
        }
        [Description("大区")]
        public class BigAreaDAta
        {
            [ParamDescription("大区ID")]
            public string DistrictID { get; set; }
            [ParamDescription("省份")]
            public string AreaID { get; set; }
        }
        [Description("用户列表")]
        private class UserList
        {
            [ParamDescription("用户ID")]
            public int UserID { get; set; }
            [ParamDescription("用户账号")]
            public string UserCode { get; set; }
            [ParamDescription("用户名称")]
            public string UserName { get; set; }
        }
    }
}
